package com.example.aliyuntest.ui;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.aliyuntest.data.Task;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TaskViewModel extends ViewModel {
    private MutableLiveData<List<Task>> mTasks = new MutableLiveData<>(new ArrayList<>());
    private long nextId = 1;
    public MutableLiveData<List<Task>> getTasks() {
        return mTasks;
    }
    public void addTask(String name) {
        List<Task> currentTasks = new ArrayList<>(Objects.requireNonNull(mTasks.getValue()));
        currentTasks.add(new Task(nextId++, name, false));
        mTasks.setValue(currentTasks);
    }

    public void removeTask(long id) {
        List<Task> currentTasks = new ArrayList<>(Objects.requireNonNull(mTasks.getValue()));
        for (Task task : currentTasks) {
            if (task.getId() == id) {
                currentTasks.remove(task);
                break;
            }
        }
        mTasks.setValue(currentTasks);
    }

    public void toggleTask(long id){
        List<Task> currentTasks = new ArrayList<>(Objects.requireNonNull(mTasks.getValue()));
        for (Task task : currentTasks) {
            if (task.getId() == id) {
                task.setDone(!task.isDone());
                break;
            }
        }
    }
}
